<?php
class Util {

  public static function objectToArray($d) {
		if (is_object($d)) {
			// Gets the properties of the given object
			// with get_object_vars function
			$d = get_object_vars($d);
		}

		if (is_array($d)) {
			/*
			* Return array converted to object
			* Using __FUNCTION__ (Magic constant)
			* for recursive call
			*/
			return array_map(array('Util','objectToArray'), $d);
		}
		else {
			// Return array
			return $d;
		}
	}

  public static function ThemePath(){
  	$CI =& get_instance();
    return base_url('themes/'.$CI->config->item("theme_name"));
  }

  public static function url_title($title=false){
  	if($title){
		$string = $title;
		$string = preg_replace("`\[.*\]`U","",$string);
		$string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$string);
		$string = str_replace('%', '-percent', $string);
		$string = htmlentities($string, ENT_COMPAT, 'utf-8');
		$string = preg_replace( "`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i","\\1", $string );
		$string = preg_replace( array("`[^a-z0-9ก-๙เ-า]`i","`[-]+`") , "-", $string);
		$string = strtolower(trim($string, '-'));
		$string = trim($string);
		return $string;
  	}else{
  		return false;
  	}
  }

  public static function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") self::rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
 }

  /*
	That it is an implementation of the function money_format for the
	platforms that do not it bear.

	The function accepts to same string of format accepts for the
	original function of the PHP.

	(Sorry. my writing in English is very bad)

	The function is tested using PHP 5.1.4 in Windows XP
	and Apache WebServer.
	*/
	public static function money_format($format, $number)
	{
	    $regex  = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'.
	              '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
	    if (setlocale(LC_MONETARY, 0) == 'C') {
	        setlocale(LC_MONETARY, '');
	    }
	    $locale = localeconv();
	    preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
	    foreach ($matches as $fmatch) {
	        $value = floatval($number);
	        $flags = array(
	            'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ?
	                           $match[1] : ' ',
	            'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
	            'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
	                           $match[0] : '+',
	            'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
	            'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
	        );
	        $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
	        $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
	        $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
	        $conversion = $fmatch[5];

	        $positive = true;
	        if ($value < 0) {
	            $positive = false;
	            $value  *= -1;
	        }
	        $letter = $positive ? 'p' : 'n';

	        $prefix = $suffix = $cprefix = $csuffix = $signal = '';

	        $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
	        switch (true) {
	            case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
	                $prefix = $signal;
	                break;
	            case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
	                $suffix = $signal;
	                break;
	            case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
	                $cprefix = $signal;
	                break;
	            case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
	                $csuffix = $signal;
	                break;
	            case $flags['usesignal'] == '(':
	            case $locale["{$letter}_sign_posn"] == 0:
	                $prefix = '(';
	                $suffix = ')';
	                break;
	        }
	        if (!$flags['nosimbol']) {
	            $currency = $cprefix .
	                        ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
	                        $csuffix;
	        } else {
	            $currency = '';
	        }
	        $space  = $locale["{$letter}_sep_by_space"] ? ' ' : '';

	        $value = number_format($value, $right, $locale['mon_decimal_point'],
	                 $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
	        $value = @explode($locale['mon_decimal_point'], $value);

	        $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
	        if ($left > 0 && $left > $n) {
	            $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
	        }
	        $value = implode($locale['mon_decimal_point'], $value);
	        if ($locale["{$letter}_cs_precedes"]) {
	            $value = $prefix . $currency . $space . $value . $suffix;
	        } else {
	            $value = $prefix . $value . $space . $currency . $suffix;
	        }
	        if ($width > 0) {
	            $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
	                     STR_PAD_RIGHT : STR_PAD_LEFT);
	        }

	        $format = str_replace($fmatch[0], $value, $format);
	    }
	    return $format;
	}


	function getTag($id = NULL){
		$CI =& get_instance();
		$CI->load->model("tag_model","tagModel");
		$result = $CI->tagModel->get($id);

		return $result[0]["name"];
	}

	function buildCategoriesList($parent, $menu)
	{
	   $html = "";
	   if (isset($menu['parents'][$parent]))
	   {
	      $html .= "
	      <ul>\n";
	       foreach ($menu['parents'][$parent] as $itemId)
	       {
	          if(!isset($menu['parents'][$itemId]))
	          {
	             $html .= "<li>\n  ".$menu['items'][$itemId]['name']."\n</li> \n";
	          }
	          if(isset($menu['parents'][$itemId]))
	          {
	             $html .= "
	             <li>\n  ".$menu['items'][$itemId]['name']." \n";
	             $html .= Util::buildCategoriesList($itemId, $menu);
	             $html .= "</li> \n";
	          }
	       }
	       $html .= "</ul> \n";
	   }
	   return $html;
	}

	function buildCategoriesListLimit($parent, $menu , $limit=99999, $level=1 ,$parentUrl = "")
	{
		$html = "";
		if (isset($menu['parents'][$parent]) AND (($level <= $limit)) )
		{
			$isActive = "";
			foreach ($menu['parents'][$parent] as $itemId)
			{
			  foreach ($this->uri->segment_array() as $key => $segment) {
			    if($menu['items'][$itemId]['url'] == urldecode($segment)){
			      $isActive = "";
			    }
			  }
			}
			if($parent != 0){
				$html .= "<ul class=\"sub-menu $isActive\">\n";
			}else{
				$html .= "<ul class=\"$isActive\">\n";
			}
			foreach ($menu['parents'][$parent] as $itemId)
			{
				$category_list = Util::getCategoryInherit($menu['items'][$itemId]['id']);
				if(!empty($category_list)){
					$category_list = array_reverse($category_list);
					foreach ($category_list as $key => $value) {
						$prepareUri[$key] = $value["url"];
					}
					$parentUrl = implode("/", $prepareUri);
					unset($prepareUri);
				}

			  if(!isset($menu['parents'][$itemId]))
			  {
			    //$html .= "<li><div class=\"image-list\"/></div> \n<a href=\"".base_url($parentUrl."/".$menu['items'][$itemId]['url'])."\" >".$menu['items'][$itemId]['name']."</a>\n</li> \n";
			    $html .= "<li> \n<a href=\"".base_url("category/".$parentUrl)."\" >".$menu['items'][$itemId]['name']."</a> \n</li> \n";
			  }
			  if(isset($menu['parents'][$itemId]))
			  {
					$html .= "<li><div class=\"image-list\"/></div> \n<a class=\"toggle\" href=\"".base_url("category/".$parentUrl)."\" > ".$menu['items'][$itemId]['name']." </a>\n <a class=\"external\" href=\"".base_url("category/".$parentUrl)."\" target=\"_blank\"><img src=\"/themes/".$this->config->item("theme_name")."/images/external.gif\" alt=\"External Link: ".$menu['items'][$itemId]['name']."\"></a>";
					$html .= Util::buildCategoriesListLimit($itemId, $menu, $limit, (++$level), $parentUrl);
					$html .= "</li> \n";
			  }
			}
			$html .= "</ul> \n";
		}
		return $html;
	}

	function buildCategoriesOptionList($parent, $menu, $level = "", $selectedID = NULL)
	{
		$html = "";
	  if (isset($menu['parents'][$parent]))
	  {
      foreach ($menu['parents'][$parent] as $itemId)
      {
				if($selectedID == $menu['items'][$itemId]['id']){
					$selected = "selected";
				}else{
					$selected = "";
				}
        if(!isset($menu['parents'][$itemId]))
        {
           $html .= "<option value=\"".$menu['items'][$itemId]['id']."\" $selected>\n $level |_ ".$menu['items'][$itemId]['name']."\n</option> \n";
        }
        if(isset($menu['parents'][$itemId]))
        {
					$html .= "<option value=\"".$menu['items'][$itemId]['id']."\" $selected>\n $level|_ ".$menu['items'][$itemId]['name']." \n";
					$html .= Util::buildCategoriesOptionList($itemId, $menu, ("|&nbsp;&nbsp;&nbsp;".$level) , $selectedID);
					$html .= "</option> \n";
        }
      }
	  }
	  return $html;
	}

	function buildCategoriesTableList($parent, $menu, $level = "")
	{
		$html = "";
	   if (isset($menu['parents'][$parent]))
	   {
	      $level .= "&nbsp;&nbsp;&nbsp;";
	       foreach ($menu['parents'][$parent] as $itemId)
	       {
	          if(!isset($menu['parents'][$itemId]))
	          {
	            	$html .= "<tr class=\"children".$parent."\">
	            	<td>\n ".$menu['items'][$itemId]['id']."\n</td>
	            	<td>\n $level |_ ".$menu['items'][$itemId]['name']."\n</td>
	            	<td>
	            		<input class=\"input-mini\" type=\"text\" name=\"sort[".$menu['items'][$itemId]['id']."]\" value=\"".$menu['items'][$itemId]['sort']."\">
	            	</td>
	            	<td>
	            	<div class=\"btn-group\">
	            		<a class=\"btn btn-default\" href=\"".base_url('admin/category/add/'.$menu['items'][$itemId]['id'])."\"><span class='glyphicon glyphicon-plus'></span></a>
									<a class=\"btn btn-default\" href=\"".base_url('admin/tag/add/'.$menu['items'][$itemId]['id'])."\"><span class='glyphicon glyphicon-pencil'></span></a>
									<a class=\"btn btn-default\" href=\"".base_url('admin/category/delete/'.$menu['items'][$itemId]['id'])."\" onClick=\"return confirm('คุณมั่นใจว่าต้องการลบ?');\"><span class='glyphicon glyphicon-minus'></span></a>
	            	</div>
	            	</td></tr> \n";
	          }
	          if(isset($menu['parents'][$itemId]))
	          {
							$html .= "
							<tr class=\"children".$parent."\">
							<td>\n ".$menu['items'][$itemId]['id']."\n</td>
							<td>\n<a class='keep' children=\"children".$menu['items'][$itemId]['id']."\" href=''>$level |_ ".$menu['items'][$itemId]['name']."</a>\n";
							$html .= "</td>
							<td>
	            	<input class=\"input-mini\" type=\"text\" name=\"sort[".$menu['items'][$itemId]['id']."]\" value=\"".$menu['items'][$itemId]['sort']."\">
	            </td>
	            <td>
	            <div class=\"btn-group\">
	            	<a class=\"btn btn-default\" href=\"".base_url('admin/category/add/'.$menu['items'][$itemId]['id'])."\"><span class='glyphicon glyphicon-plus'></span></a>
	            	<a class=\"btn btn-default\" href=\"".base_url('admin/tag/add/'.$menu['items'][$itemId]['id'])."\"><span class='glyphicon glyphicon-pencil'></span></a>
	             	<a class=\"btn btn-default\" href=\"".base_url('admin/category/delete/'.$menu['items'][$itemId]['id'])."\" onClick=\"return confirm('คุณมั่นใจว่าต้องการลบ?');\"><span class='glyphicon glyphicon-minus'></span></a>
							</div>
							</td></tr> \n";
	             $html .= Util::buildCategoriesTableList($itemId, $menu, $level);
	          }
	       }
	   }
	   return $html;
	}

	function buildForumCategoriesTableList($parent, $menu, $level = "")
	{
		$html = "";
	   if (isset($menu['parents'][$parent]))
	   {
	      $level .= "&nbsp;&nbsp;&nbsp;";
	       foreach ($menu['parents'][$parent] as $itemId)
	       {
	          if(!isset($menu['parents'][$itemId]))
	          {
	            	$html .= "<tr class=\"children".$parent."\">
	            	<td>\n ".$menu['items'][$itemId]['id']."\n</td>
	            	<td>\n $level |_ ".$menu['items'][$itemId]['name']."\n</td>
	            	<td>
	            		<input class=\"input-mini\" type=\"text\" name=\"sort[".$menu['items'][$itemId]['id']."]\" value=\"".$menu['items'][$itemId]['sort']."\">
	            	</td>
	            	<td>
	            		<a href=\"".base_url('admin/forum/addcategory/'.$menu['items'][$itemId]['id'])."\"><img src=\"".Util::ThemePath()."/images/btn-add.png\" width=\"18\" /></a> | 
									<a href=\"".base_url('admin/forum/editcategory/'.$menu['items'][$itemId]['id'])."\"><img src=\"".Util::ThemePath()."/images/edit.png\"  /></a> | 
									<a href=\"".base_url('admin/forum/deletecategory/'.$menu['items'][$itemId]['id'])."\" onClick=\"return confirm('คุณมั่นใจว่าต้องการลบ?');\"><img src=\"".Util::ThemePath()."/images/x.png\" width=\"20\" height=\"20\" /></a> &nbsp; 
	            	</td></tr> \n";
	          }
	          if(isset($menu['parents'][$itemId]))
	          {
							$html .= "
							<tr class=\"children".$parent."\">
							<td>\n ".$menu['items'][$itemId]['id']."\n</td>
							<td>\n<a class='keep' children=\"children".$menu['items'][$itemId]['id']."\" href=''>$level |_ ".$menu['items'][$itemId]['name']."</a>\n";
							$html .= "</td>
							<td>
	            	<input class=\"input-mini\" type=\"text\" name=\"sort[".$menu['items'][$itemId]['id']."]\" value=\"".$menu['items'][$itemId]['sort']."\">
	            </td>
	            <td>
	            	<a href=\"".base_url('admin/forum/addcategory/'.$menu['items'][$itemId]['id'])."\"><img src=\"".Util::ThemePath()."/images/btn-add.png\" width=\"18\" /></a> | 
	            	<a href=\"".base_url('admin/forum/editcategory/'.$menu['items'][$itemId]['id'])."\"><img src=\"".Util::ThemePath()."/images/edit.png\"  /></a> | 
	             	<a href=\"".base_url('admin/forum/deletecategory/'.$menu['items'][$itemId]['id'])."\" onClick=\"return confirm('คุณมั่นใจว่าต้องการลบ?');\"><img src=\"".Util::ThemePath()."/images/x.png\" width=\"20\" height=\"20\" /></a> &nbsp; 
							</td></tr> \n";
	             $html .= Util::buildForumCategoriesTableList($itemId, $menu, $level);
	          }
	       }
	   }
	   return $html;
	}

	function _getCategoryInherit($category_id = NULL, $categoryList = NULL){
		if($category_id == NULL){
			return false;
		}
		
		$this->load->model("category_model","categoryModel");
		$category = $this->categoryModel->get(array("where"=>array("id"=>$category_id)));
		if($category[0]["parent_id"] == 0){
			$categoryList[] = $category[0];
		}
		if($category[0]["parent_id"] > 0){
			$categoryList[] = $category[0];
			$categoryList = Util::_getCategoryInherit($category[0]["parent_id"],$categoryList);
		}

		return $categoryList;
	}

	function getCategoryInherit($category_id = NULL, $categoryList = NULL){
		if($category_id == NULL){
			return false;
		}
		
		if($categoryList = $this->cache->get("category/category_inherit_".$category_id)){
			return $categoryList;
		}
		
		$categoryList = Util::_getCategoryInherit($category_id,$categoryList);
		
		$this->cache->write($categoryList,"category/category_inherit_".$category_id,0);
		
		return $categoryList;
	}

	function _getCategoryInheritByParent($category_id = NULL, $categoryList = NULL){
		if($category_id == NULL){
			return false;
		}
		$this->load->model("category_model","categoryModel");
		$category = $this->categoryModel->get(array("where"=>array("parent_id"=>$category_id)));
		if(!empty($category)){
			foreach ($category as $key => $value) {
					$categoryList[] = $value;
					$categoryList = Util::_getCategoryInheritByParent($value["id"],$categoryList);
			}
		}
		return $categoryList;
	}

	function getCategoryInheritByParent($category_id = NULL, $categoryList = NULL){
		if($category_id == NULL){
			return false;
		}

		if($categoryList = $this->cache->get("category/category_inheritbyparent_".$category_id)){
			return $categoryList;
		}

		$categoryList = Util::_getCategoryInheritByParent($category_id,$categoryList);

		$this->cache->write($categoryList,"category/category_inheritbyparent_".$category_id,0);
		return $categoryList;
	}

	function findCategoryTree($categoryArrayDirty = "", $categoryArray = ""){
		$returnValue = NULL;
		if(!empty($categoryArray)){
			foreach ($categoryArray as $key2 => $value2) {
				foreach ($categoryArrayDirty as $key => $value) {
					if($value["tag_id"] == $value2["tag_id"]){
						$returnValue[$value2["tag_id"]] = $value2;
					}
				}
			}
		}

		return $returnValue;
	}

	function getPostMeta($post_id = NULL){
		if($post_id == NULL){
			return false;
		}
		$returnList = false;
		$this->load->model("postmeta_model","postmetaModel");
		$postmetas = $this->postmetaModel->get(array("where"=>array("pos_id"=>$post_id)));

		if(!empty($postmetas)) {
			foreach ($postmetas as $metaKey => $metaValue) {
				$returnList[$metaValue["key"]] = $metaValue["value"];
			}
		}
		return $returnList;
	}

	function getProvince($id = NULL){
		if($id == NULL){
			return FALSE;
		}
		$list = $this->config->item("province");
		if(!empty($list[$id])){
			return $list[$id];
		}
	}

	function getType($id = NULL){
		if($id == NULL){
			return FALSE;
		}
		$this->load->model("type_model","typeModel");
		$gettype['where']['id'] = $id;
		$type = $this->typeModel->get($gettype);
		return $type[0];
	}

	function getCommentCount($id = NULL){
		if($id == NULL){
			return FALSE;
		}
		$this->load->model("comment_model","commentModel");
		$getComment['where']['pos_id'] = $id;
		$getComment['where']['status'] = 1;
		$comment = $this->commentModel->get($getComment);
		if(!empty($comment)){
			return count($comment);
		}else{
			return 0;
		}
	}

	function getSubCategory($parent_id = NULL){
		if($parent_id == NULL){
			return false;
		}
		
		$this->load->model("category_model","categoryModel");
		$whereClean["where"]["parent_id"] = $parent_id;
		$whereClean["order"] = "sort ASC";
		$subCategoryList = $this->categoryModel->get($whereClean);
		if(!empty($subCategoryList)){
			return $subCategoryList;
		}else{
			return false;
		}
	}



	function ezDate($d) {
    $ts = time() - strtotime(str_replace("-","/",$d));
    if($ts>31536000) $val = round($ts/31536000,0).' ปีที่แล้ว';
    else if($ts>2419200) $val = round($ts/2419200,0).' เดือนที่แล้ว';
    else if($ts>604800) $val = round($ts/604800,0).' สัปดาห์ที่แล้ว';
    else if($ts>86400) $val = round($ts/86400,0).' วันที่แล้ว';
    else if($ts>3600) $val = round($ts/3600,0).' ขั่วโมงที่แล้ว';
    else if($ts>60) $val = round($ts/60,0).' นาทีที่แล้ว';
    else $val = $ts.' วินาทีที่แล้ว';
    return $val;
  }


	function getForumCategoryInherit($category_id = NULL, $categoryList = NULL){
		if($category_id == NULL){
			return false;
		}
		$this->load->model("forumcategory_model","forumcategoryModel");
		$category = $this->forumcategoryModel->get(array("where"=>array("id"=>$category_id)));
		if($category[0]["parent_id"] == 0){
			$categoryList[] = $category[0];
		}
		if($category[0]["parent_id"] > 0){
			$categoryList[] = $category[0];
			$categoryList = Util::getForumCategoryInherit($category[0]["parent_id"],$categoryList);
		}
		return $categoryList;
	}

	function blindIP($ip = NULL){
		if($ip == NULL){
			return "";
		}

		$ip = explode(".", $ip);
		$ip[count($ip)-1] = "xxx";

		return implode(".", $ip);
	}

	function renderPost($posts = NULL){
		return $this->parser->parse("/_Includes/_postListView.php", array("posts"=>$posts), TRUE);
	}

	function thai_date($time){
		$thai_day_arr=array("อาทิตย์","จันทร์","อังคาร","พุธ","พฤหัสบดี","ศุกร์","เสาร์");
		$thai_month_arr_full=array(
		 "0"=>"",
		 "1"=>"มกราคม",
		 "2"=>"กุมภาพันธ์",
		 "3"=>"มีนาคม",
		 "4"=>"เมษายน",
		 "5"=>"พฤษภาคม",
		 "6"=>"มิถุนายน",
		 "7"=>"กรกฎาคม",
		 "8"=>"สิงหาคม",
		 "9"=>"กันยายน",
		 "10"=>"ตุลาคม",
		 "11"=>"พฤศจิกายน",
		 "12"=>"ธันวาคม"
		);
		$thai_month_arr=array(
		 "0"=>"",
		 "1"=>"ม.ค.",
		 "2"=>"ก.พ.",
		 "3"=>"มี.ค.",
		 "4"=>"เม.ย.",
		 "5"=>"พ.ค.",
		 "6"=>"มิ.ย.",
		 "7"=>"ก.ค.",
		 "8"=>"ส.ค.",
		 "9"=>"ก.ย.",
		 "10"=>"ต.ค.",
		 "11"=>"พ.ย.",
		 "12"=>"ธ.ค."
		);
		$time=strtotime($time);
		global $thai_day_arr,$thai_month_arr;
		 $thai_date_return = date("j",$time);
		 $thai_date_return.= " ".$thai_month_arr[date("n",$time)];
		 $thai_date_return.= " ".(date("Y",$time)+543);
		 return $thai_date_return;
	}

	function getParentComment($id = NULL){
		$CI =& get_instance();
		$CI->load->model("comment_model","commentModel");
		$where["order"] = "cr_date";
		$where["where"]["parent_id"] = $id;
		$result = $CI->commentModel->getUsr($where);

		return $result;
	}

	function getPercentRate($rate = NULL){
		
		$result = (100*$rate)/5;

		return $result;
	}

	function cutContent($content = NULL){
		$text=strip_tags($content);
        $num_text=strlen($text);                 
        if($num_text > 400){                                            
            $text=strip_tags(iconv_substr($text,0,400,'utf-8')).'…';                                 
        }                                              

		return $text;
	}

	function CommentCount($id = NULL){
		if($id == NULL){
			return FALSE;
		}
		$CI =& get_instance();
		$CI->load->model("comment_model","commentModel");
		$where["where"]["status"] = "1";
		$where["where"]["pos_id"] = $id;
		$result = $CI->commentModel->get($where);

		if(!empty($result)){
			return count($result);
		}else{
			return 0;
		}
	}

	function LikeCount($id = NULL){
		if($id == NULL){
			return FALSE;
		}
		$CI =& get_instance();
		$CI->load->model("like_model","likeModel");
		$where["where"]["status"] = "1";
		$where["where"]["pos_id"] = $id;
		$result = $CI->likeModel->get($where);

		if(!empty($result)){
			return count($result);
		}else{
			return 0;
		}
	}

}

?>